package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.memberDto.FamilyMemberDto;
import com.zzyl.nursing.service.member.IWeChatService;
import com.zzyl.nursing.vo.memberVo.LoginVo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-24
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{

    static final List<String> auspiciousNames = Arrays.asList(
            "春华秋实",
            "锦绣前程",
            "光明磊落",
            "瑞气盈门",
            "福星高照",
            "鸿运当头"
    );
    @Autowired
    private IWeChatService iWeChatService;
    @Autowired
    private TokenService tokenService;


    @Override
    public LoginVo login(FamilyMemberDto familyMemberDto) {

        // 获取 OpenId （家属身份唯一凭证）
        String openId = iWeChatService.getOpenId(familyMemberDto.getCode());
        // 根据OpenId 查询该家属信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));
        // 判断该家属信息是否存在
        if(ObjectUtil.isEmpty(familyMember)){
            familyMember = FamilyMember.builder().openId(openId).build();
            // 不存在创建该家属信息 并赋值 OpenId
//            familyMember.setOpenId(openId);
        }

        // 获取家属手机号
        String phone = iWeChatService.getPhone(familyMemberDto.getPhoneCode());
        familyMember.setPhone(phone);
        // 新增或更新家属信息
        saveOrUpdateFamilyMember(familyMember);
        // 将家属Id,nickName封装到Jwt中
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        String token = tokenService.createToken(claims);
        // 返回 LoginVo

        return new LoginVo(token, familyMember.getName());
    }

    /**
     * 新增或更新家属信息
     * @param familyMember
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember) {
        if(ObjectUtil.isEmpty(familyMember.getId())){
            // 家属名称由 名称列表中随机出来一个  加上  家属手机号后4位
            String name = auspiciousNames.get((int)(Math.random() * auspiciousNames.size())) + familyMember.getPhone().substring(familyMember.getPhone().length() - 4);
            familyMember.setName(name);
            // 新增
            save(familyMember);
            return;
        }
        // 更新
        updateById(familyMember);
    }
}
